function C=eyelink2_quad_plot105(file_names)
% to check for error trials
% 2005-mar-16: added accuracy & max speed

if nargin==0
    clc
    clear
    files = dir('*C.mat'); % find all files with the eye extention
    files.name;
    if length(files)==0
        disp(' ');
        disp('there are no *C.mat files in this folder:')
        cd
        uimenufcn(gcf,'WindowCommandWindow');
        return
    end
else
    if isstruct(file_names)
        files=file_names;
    else
        for i=1:size(file_names,1)
            files(i).name=file_names(i,:);
        end
    end%if isstruct(file_names)
end
scnsize = get(0,'ScreenSize');
redraw=8;

t = (0:.001:1)'*2*pi;
cir_x = sin(t).*3;
cir_y = cos(t).*3;


sac_view_align=0;
center_saccade=0;
file=1;
while file<=length(files)
    temp_gca=0;
    load(files(file).name)
    if length(C.iti)<length(C.anti)
        error('this block was not finished! truncate unused C data... and try again')        
    end
    if ~isfield(C,'corrective_sac')
        C.corrective_sac(length(C.srt))=0;
    end
    [vel_x1 vel_y1 speed1]=velocity_speed(C.eye_x,C.eye_y,C.time);
    MBD=mean(diff(C.time));% Milliseconds Between Data; so all data, even at different Hz, displays the same;
    if ~isfield(C,'quad')
        C.quad((C.ang_ecc(:,1)== 45&C.anti==0)|(C.ang_ecc(:,1)==225&C.anti==1))=1;
        C.quad((C.ang_ecc(:,1)==135&C.anti==0)|(C.ang_ecc(:,1)==315&C.anti==1))=2;
        C.quad((C.ang_ecc(:,1)==225&C.anti==0)|(C.ang_ecc(:,1)== 45&C.anti==1))=3;
        C.quad((C.ang_ecc(:,1)==315&C.anti==0)|(C.ang_ecc(:,1)==135&C.anti==1))=4;
    end
    c=C.colors;
    if ~isfield(C,'error')
        C.error=zeros(size(C.quad));
    end
    sac_quad=1;
    duration=unique(C.duration);
    disp(['there are ' num2str(length(duration)) ' fixation durations'])
    fix_dur=1;
    plot_which=0;
    fig(1);clf;
    set(1,'position',[1 31 scnsize(3)  scnsize(4)*.895],'name',[files(file).name ' (' num2str(file) ' of ' num2str(length(files)) ' files)'],'NumberTitle','off');
    h_trial_plot=subplot('Position',[0.0571429 0.540476 0.919643 0.433333]);cla;tickout;hold on;axis ij
    h_eyetrace_plot=subplot('Position',[0.6518 0.0476 0.3321 0.4190]);cla;hold on;tickout;axis square; axis([-20.5 20.5 -20.5 20.5]);fill([-22 22 22 -22],[22 22 -22 -22],[.8 .8 .8]);
    h=text(-19,19, 'PRO ');set(h,'FontWeight','bold','color',C.colors.PRO)
    h=text(-19,17, 'ANTI');set(h,'fontweight','bold','color',C.colors.ANTI)                
    h_saccade_view=subplot('Position',[0.0553571 0.052381 0.573214 0.407143]);cla;hold on;tickout;
    
    f = uimenu('Label','Keyboard Commands');
    uimenu(f,'Label','s = Save Data');
    uimenu(f,'Label','n = Next Quad');
    uimenu(f,'Label','b = Previous Quad');
    uimenu(f,'Label','N = Next File');
    uimenu(f,'Label','B = Previous File'); 
    uimenu(f,'Label','a = Set Current X&Y on Trial Plot to Zero');
    uimenu(f,'Label','g = Goto File #');
    uimenu(f,'Label','p = Pause');
    uimenu(f,'Label','Esc = exit program');
    lm=uimenu(f,'Label','Left Mouse');
      uimenu(lm,'Label','Trial Plot = Select One or All Trials');
      uimenu(lm,'Label','Eye Trace Plot = Toggle Alignment: Saccade or Target Onset');
      uimenu(lm,'Label','Eye + Target Plot = Toggle Saccade Centering');
    rm=uimenu(f,'Label','Right Mouse');
      uimenu(rm,'Label','Trial Plot = Error Reporting');
      uimenu(rm,'Label','Eye Trace Plot = Redefine Saccade Onset (single trial only)');
      uimenu(rm,'Label','Eye + Target Plot = Nothing Yet');
    
    while sac_quad<5
        fig(1)
        if fix_dur
            which_trials=find(C.quad==sac_quad & C.duration'==duration(fix_dur));
        else
            which_trials=find(C.quad==sac_quad ); % plot all durations
        end
        % order plot by fixation duration
        
        [val loc]=sort(round((C.fix_off(which_trials)-C.fix_on(which_trials))/20)*20);
        which_trials=which_trials(loc);
        [val loc]=sort(C.anti(which_trials));
        which_trials=which_trials(loc);
        if ~plot_which
            plot_which=which_trials;
            plot_which(C.error(plot_which)>0)=[];
        end
        if redraw==1 | redraw==3  | redraw==5  | redraw==8
            subplot(h_trial_plot);cla;axis auto;
        end
        if redraw==2 | redraw==3  | redraw==6  | redraw==8
            subplot(h_eyetrace_plot);cla;fill([-17 17 17 -17],[17 17 -17 -17],[.8 .8 .8]);
            axis([-15.5 15.5 -15.5 15.5]);
        end
        if redraw==4 | redraw==5  | redraw==6  | redraw==8
            subplot(h_saccade_view);cla;axis auto;
        end
        for tr_num=which_trials
            if C.anti(tr_num)
                cuecolor=C.colors.ANTI;
            else
                cuecolor=C.colors.PRO;
            end
            range1=C.e_start(tr_num):C.e_end(tr_num);
            range2=range1(C.blink(range1)>5)-min(range1)+1;
            t_align=C.fix_on(tr_num);
            time=round(C.time(range1)-t_align);
            eye_x=C.eye_x(range1)-C.x_adj(tr_num);
            eye_y=C.eye_y(range1)-C.y_adj(tr_num);
            eye_x_raw=C.eye_x_raw(range1)-C.x_adj(tr_num);
            eye_y_raw=C.eye_y_raw(range1)-C.y_adj(tr_num);
            speed=speed1(range1);
            blink=C.blink(range1);
            which=find(tr_num==which_trials);
            %%%%%%%%%%%%%%
            
            if redraw==1 | redraw==3  | redraw==5  | redraw==8
                subplot(h_trial_plot);axis auto;  hold on;        
                title(['Fixation Delay #' num2str(fix_dur)])
                if tr_num<24; xlim([round(min(time)/200)*200 round(max(time)/200)*200]);end;
                ylim([which-.5 which+.5]);
                xlim([-1000 4000]);
                hline(which,'k');
                vline([C.fix_on(tr_num) C.fix_off(tr_num)]-t_align,'k');
                vfill(C.cue_tgt_on(tr_num)-t_align, C.cue_tgt_off(tr_num)-t_align,cuecolor);
                if C.corrective_sac(tr_num)>0
                    vline(C.corrective_sac(tr_num)+C.cue_tgt_on(tr_num)-t_align,'-.k');
                end
                vline(C.fix_off(tr_num)-t_align,'--k');
                if C.error(tr_num)
                    plot(time,-(eye_x_raw/40)+which ,'color',[.8 1 1]);
                    plot(time,-(eye_y_raw/40)+which ,'color',[1 .8 1]);
                    plot(time,-(eye_x/40)+which ,'.-','color',[0 .3 .4]);
                    plot(time,-(eye_y/40)+which ,'.-','color',[.4 0 .3]);
                    plot(time(range2),-(eye_x_raw(range2)/40)+which ,'.','color',[.8 1 1]);
                    plot(time(range2),-(eye_y_raw(range2)/40)+which ,'.','color',[1 .8 1]);
                    plot(time(range2),-(eye_x(range2)/40)+which ,'.','color',[0 .7 .7]);
                    plot(time(range2),-(eye_y(range2)/40)+which ,'.','color',[.7 0 .7]);
                    switch   C.error(tr_num)
                        case 1, e_text=('1) Premature/Double Saccade');
                        case 2, e_text=('2) No Saccade/Late Saccade');
                        case 3, e_text=('3) Pro/Anti switch');
                        case 4, e_text=('4) Double Saccade & Pro Anti Switch');
                        case 5, e_text=('5) Loss of Eye Tracking');
                        case 5, e_text=('6) Misc. Error');
                    end
                    text(50,which-.25,e_text)
                else
                    plot(time,-(eye_x_raw/40)+which ,'color',[.8 1 1]);
                    plot(time,-(eye_y_raw/40)+which ,'color',[1 .8 1]);
                    plot(time,-(eye_x/40)+which ,'.-c');
                    plot(time,-(eye_y/40)+which ,'.-m');
                    plot(time(range2),-(eye_x_raw(range2)/40)+which ,'.','color',[.8 1 1]);
                    plot(time(range2),-(eye_y_raw(range2)/40)+which ,'.','color',[1 .8 1]);
                    plot(time(range2),-(eye_x(range2)/40)+which ,'.','color',[0 .5 .5]);
                    plot(time(range2),-(eye_y(range2)/40)+which ,'.','color',[.5 0 .5]);
                end
                vline(C.time(C.sac_on_loc(tr_num))-t_align,'-.g');
                hline(which+.5);
                ylim([.5 which+.5]);box on
                set(gca,'yticklabel',which_trials,'ytick',1:length(which_trials))
                ylabel('Trial Number')
                
            end% if redraw==1 | 4
            %%%%%%%%%%%%%%
            if redraw==2 | redraw==3  | redraw==6  | redraw==8
                if  sum(tr_num==plot_which)
                    subplot(h_eyetrace_plot);
                    vline([-15 0 15],'c');
                    hline([-15 0 15],'m');
                    plot(0,0,'.k');
                    plot(0,0,'ok');
                    h=text(-14,14, 'PRO ');set(h,'FontWeight','bold','color',C.colors.PRO)
                    h=text(-14,12, 'ANTI');set(h,'fontweight','bold','color',C.colors.ANTI)                
                    if tr_num==plot_which(1)
                        for i=1:4
                            m_x=mean(C.eye_x(C.sac_off_loc(C.quad==i & C.error==0))-C.x_adj(C.quad==i & C.error==0)');
                            m_y=mean(C.eye_y(C.sac_off_loc(C.quad==i & C.error==0))-C.y_adj(C.quad==i & C.error==0)');                            
                            cir_x1=cir_x+m_x;
                            cir_y1=cir_y+m_y;
                            plot(cir_x1,cir_y1,'k');
                        end
                    end
                    
                    [val loc1]=minfix((C.time(C.sac_on_loc(tr_num))-t_align)-time );
                    [val loc2]=minfix((C.time(C.sac_off_loc(tr_num))-t_align)-time );
                    if C.sac_on_loc(tr_num)==0
                        [val loc1]=minfix((C.fix_off(tr_num)-t_align)-time );
                        [val loc2]=minfix((C.fix_off(tr_num)-t_align)-time );
                    end
                    show_sac_range=max(1,loc1-5):min([loc1+(500/MBD); length(time)]);
                    
                    temp=floor(speed(show_sac_range)/25);
                    %plot(eye_x(show_sac_range),eye_y(show_sac_range),'k')
                    fred=[1-1/1.75 1-1/1.5 1-1/2 1-1/4 1-1/8 1-1/16 1-1/32 1-1/64 1];
                    switch center_saccade
                        case 0 % as is
                            adj_x=0;
                            adj_y=0;
                        case 1 % set start as zero
                            adj_x=eye_x(loc1);
                            adj_y=eye_y(loc1);
                    end %switch center_saccade
                    for i=min(temp):max(temp)
                        x2=eye_x(show_sac_range)-adj_x;
                        y2=eye_y(show_sac_range)-adj_y;
                        killer=zeros(size(y2));
                        killer(unique([find(temp==i);find(temp(1:end-1)==i)+1]))=1;                       
                        x2(~killer)=NaN;
                        y2(~killer)=NaN;
                        plot(x2,y2,'color',cuecolor*fred(min(i+1,length(fred))) );                                                
                    end
                    clear killer    
%                     for i=2:length(show_sac_range)
%                     plot(eye_x(show_sac_range(i-1:i)),eye_y(show_sac_range(i-1:i)),'-','color',cuecolor*fred(min(temp(i)+1,length(fred))));%[0 fred(min([10; temp(i)+1]))  0]);
%                     end
                    [tgt_x tgt_y]=polar2cart(C.ang_ecc(tr_num,:));
                    if C.peri(tr_num)
                        tgt(1)=plot(tgt_x,tgt_y,'.','color',cuecolor,'markersize',18);
                        title('Peripheral');
                    else
                        tgt(1)=plot(tgt_x,tgt_y,'o','color',cuecolor);
                        title('Central');
                    end       
                    plot(eye_x(loc1)-adj_x,eye_y(loc1)-adj_y,'ow')
                    plot(eye_x(loc2)-adj_x,eye_y(loc2)-adj_y,'ow')
                    %plot(C.eye_x(C.sac_off_loc(tr_num))-C.x_adj(tr_num),C.eye_y(C.sac_off_loc(tr_num))-C.y_adj(tr_num),'wo')

                end% if  sum(tr_num==plot_which)
                
            end %if redraw==2 | redraw==5 | redraw==8
            
            %%%%%%%%%%%%%%
            if redraw==4 | redraw==5 | redraw==6 | redraw==8
                subplot(h_saccade_view);
                if sum(tr_num==plot_which) % plot only one or all saccades
                    
                    ylim([-20 20]);
                    if sac_view_align & C.sac_on_loc(tr_num)>0
                        [val loc3]=minfix((C.time(C.sac_on_loc(tr_num))-t_align)-time );
                        val=time(loc3);
                        loc3=loc3-round(500/MBD);%specific for london data
                        view_sac_range=loc3:min([loc3+round(1000/MBD); length(time)]);%specific for london data
                        vline(0);
                        %p_sac_off=C.sac_off(tr_num)-C.sac_on(tr_num);
                        p_sac_off=C.time(C.sac_off_loc(tr_num))-C.cue_tgt_on(tr_num)-C.srt(tr_num);                        
                        c_sac_on=C.corrective_sac(tr_num)-C.srt(tr_num);
                        sac_on_loc =find(time(view_sac_range)-val==0);
                        sac_off_loc=find(time(view_sac_range)-val==p_sac_off);                        
                        title('saccade aligned');
                        xlim([-500 500]);
                    else                
                        colors=[C.colors.PRO; C.colors.ANTI];
                        [val loc3]=minfix((C.cue_tgt_on(tr_num)-t_align)-time );
                        val=time(loc3)+val;  
                        view_sac_range=loc3:min([loc3+(1000/MBD); length(time)]); %specific for eyelinkII data
                        vline(C.srt(tr_num),colors(C.anti(tr_num)+1,:));
                        % p_sac_on=C.srt(tr_num);
                        p_sac_off=C.time(C.sac_off_loc(tr_num))-C.cue_tgt_on(tr_num);
                        c_sac_on=C.corrective_sac(tr_num);
                        sac_on_loc =find(time(view_sac_range)-val==C.srt(tr_num));
                        sac_off_loc=find(time(view_sac_range)-val==p_sac_off);
                        title('target onset aligned');
                        xlim([0 1000]);
                    end
                    if isempty(sac_on_loc) | isempty(sac_off_loc)
                        sac_on_loc=1;
                        sac_off_loc=1;
                    end
                    [C.max_speed(tr_num) sloc]=max(speed(view_sac_range(sac_on_loc:sac_off_loc))); 
                    C.sac_start_x(tr_num)=eye_x(view_sac_range(sac_on_loc));
                    C.sac_start_y(tr_num)=eye_y(view_sac_range(sac_on_loc));
                    C.sac_end_x(tr_num)=eye_x(view_sac_range(sac_off_loc));
                    C.sac_end_y(tr_num)=eye_y(view_sac_range(sac_off_loc));
                    
                    if length(plot_which)==1
                        vline(time(view_sac_range(sloc+sac_on_loc-1))-val);
                        vline(p_sac_off,'k');
                        if C.corrective_sac(tr_num)>0
                            vline(c_sac_on,'-.k');
                        end
                        
                        hline((C.sac_thres(tr_num)/20)-20);
                        hline((50/20)-20,'--');
                        plot(time(view_sac_range)-val,(speed(view_sac_range)/20)-20,'.-','color',[0 1 0]);
%                         subplot(h_eyetrace_plot);
%                         plot(C.sac_start_x(tr_num),C.sac_start_y(tr_num),'wo')
%                         plot(C.sac_end_x(tr_num),C.sac_end_y(tr_num),'wo')
%                         subplot(h_saccade_view);
                    end
                    view_sac_range2=view_sac_range(blink(view_sac_range)>4);
                    if ~isempty(view_sac_range2) & length(plot_which)==1
                        plot(time(view_sac_range)-val,eye_x_raw(view_sac_range),'color',[.8 1 1]);
                        plot(time(view_sac_range)-val,eye_y_raw(view_sac_range),'color',[1 .8 1]);
                    end
                    plot(time(view_sac_range)-val,eye_x(view_sac_range),'.-c');
                    plot(time(view_sac_range)-val,eye_y(view_sac_range),'.-m');
                    if ~isempty(view_sac_range2) & length(plot_which)==1
                        plot(time(view_sac_range2)-val,eye_x_raw(view_sac_range2),'.','color',[.8 1 1]);
                        plot(time(view_sac_range2)-val,eye_y_raw(view_sac_range2),'.','color',[1 .8 1]);
                        plot(time(view_sac_range2)-val,eye_x(view_sac_range2),'.','color',[0 .5 .5]);
                        plot(time(view_sac_range2)-val,eye_y(view_sac_range2),'.','color',[.5 0 .5]);
                    end                    
                end
            end%if redraw==3 | redraw==4
            %%%%%%%%%%%%%%
            
        end% tr_num
        %%%%%%%%%%%%%%
        if temp_gca;subplot(temp_gca);end
        redraw=0; %dont  assume to redraw
        [x,y,button] = ginput(1);
        if length(button)==0;
            button='return'; %if you hit enter: button=[]
        end
        temp_gca=gca;
        uistate = uiunsuspend(1);% a sub function i touched up to reenable the zoom (and other) functions; 
        switch button
            case 1, % left mouse button should select the saccade to be viewed 
                if (sum(x<get(gca,'xlim'))==1 & sum(y<get(gca,'ylim'))==1) % in current plot's lim's               
                    switch gca % get current axis (built-in function) 
                        case h_trial_plot % top xy position plot
                            if length(plot_which)==1 & plot_which==which_trials(round(y))
                                plot_which=which_trials; %plot all;
                                plot_which(C.error(plot_which)>0)=[];
                            else
                                plot_which=which_trials(round(y));%plot one
                            end
                            redraw=6;
                        case h_eyetrace_plot, %lower right
                            center_saccade=abs(center_saccade-1) % toggle sac v tgtoff align
                            redraw=2;
                        case h_saccade_view %lower left
                            sac_view_align=abs(sac_view_align-1) % toggle sac v tgtoff align
                            redraw=4;
                    end % switch which plot is current
                end % if in current plot's lim's                
            case 3 % right button
                if (sum(x<get(gca,'xlim'))==1 & sum(y<get(gca,'ylim'))==1) % in current plot's lim's
                    switch gca
                        case h_trial_plot % top xy position plot
                            redraw=8;
                            %                             if C.error(which_trials(round(y)))==0
                            %C.error(which_trials(round(y)))=abs(C.error(which_trials(round(y)))-1);% toggle error
                            uimenufcn(gcf,'WindowCommandWindow');
                            fred={'Correct Trial','Premature/Double Saccade', 'No Saccade/Late Saccade','Pro/Anti switch','fMRI noise','Loss of Eye Tracking'};
                            %                                 clc;
                            %                                 disp(['Current Status: ' char(fred(C.error(which_trials(round(y)))+1))])
                            %                                 disp('---------------')
                            %                                 disp('1) Premature/Double Saccade')
                            %                                 disp('2) No Saccade')
                            %                                 disp('3) Pro/Anti switch')
                            %                                 disp('4) fMRI noise')
                            %                                 a=input(['Error Type(0:4): ' ],'s');
                            a='z';
                            while ~any(a(1)==['0123456'])
                                clc;
                                disp(['Current Status: ' char(fred(C.error(which_trials(round(y)))+1))])
                                disp('---------------')
                                disp('1) Premature/Double Saccade')
                                disp('2) No Saccade/Late Saccade')
                                disp('3) Pro/Anti switch')
                                disp('4) Double Saccade & Pro/Anti Switch');
                                disp('5) Loss of Eye Tracking')
                                disp('6) Misc. Error')                                
                                a=input(['Error Type(0:5): ' ],'s');
                                if isempty(a),
                                    a=num2str(C.error(which_trials(round(y)))),
                                    redraw=0;
                                end
                            end
                            clear fred;
                            C.error(which_trials(round(y)))=str2num(a(1));
                            if any(a(1)==['134'])
                                C=corrective_srt(C,which_trials(round(y)));
                            end
                            fig(1);                                              
                            if length(plot_which)==1
                                plot_which=which_trials; %plot all;
                            end
                            plot_which(C.error(plot_which)>0)=[];
                            %                             else
                            %                                 C.error(which_trials(round(y)))=0;
                            %                                 plot_which=which_trials; %plot all;
                            %                                 plot_which(C.error(plot_which)>0)=[];                            
                            %                             end
                        case h_eyetrace_plot, %lower right
                            %do nothing for now
                        case h_saccade_view %lower left
                            if length(plot_which)==1
                                C=refind_saccade_internal(C,plot_which);
                            end
                            redraw=8;
                    end % switch which plot is current
                end % if in current plot's lim's                
            case 27, 
                %ESC button
                set(1,'position',[scnsize(3)/3 scnsize(4)/3 scnsize(3)/3 scnsize(4)/3])
                return;    
            case 48 % numkey 0
                fix_dur=0;
                plot_which=0;
                redraw=8;                
            case 49 % numkey 1
                fix_dur=1;
                plot_which=0;
                redraw=8;                
            case 50 % numkey 2
                fix_dur=2;
                plot_which=0;
                redraw=8;                
            case 51 % numkey 3
                fix_dur=3;
                plot_which=0;
                redraw=8;                
            case 52 % numkey 4
                fix_dur=4;
                plot_which=0;
                redraw=8;                
            case 53 % numkey 5
                fix_dur=5;
                plot_which=0;
                redraw=8;                
            case 66 % B for previous file
                sac_quad=100;
                file=max([1 file-1]);
                redraw=8;                
            case 78 % N for next file
                sac_quad=100;
                file=file+1;    
                redraw=8;                
            case 97, % a for adjust
                if gca==h_trial_plot % top trial by trial xy position plot
%                     round(x);
%                     round(y);
                    range1=C.e_start( which_trials(round(y))):C.e_end( which_trials(round(y)));
                    t_align=C.fix_on( which_trials(round(y)));
                    time=round(C.time(range1)-C.fix_on( which_trials(round(y))));
                    eye_x=C.eye_x(range1);
                    eye_y=C.eye_y(range1);
                    
                    which_trials(round(y))
                    [val loc]=minfix(x-time)
                    x=time(loc);
                    C.x_adj(which_trials(round(y)))=eye_x(find(time==round(x)));
                    C.y_adj(which_trials(round(y)))=eye_y(find(time==round(x)));
                    redraw=8;
                end

            case 98, % b for back
                sac_quad=max([1 sac_quad-1]); 
                fix_dur=1;
                %       redraw=1;
                %       find_tgt_sac=1; 
                %       find_all_sac=1;
                plot_which=0;                
                redraw=8;                
            case 103, % g for goto
                pause(0.01); % prevents flickering between windows
                clc; 
                %how do i send command window to the front? you'd thing input would do this automatically, right!
                uimenufcn(gcf,'WindowCommandWindow');
                clc;
                a=input(['\nGoTo File Number(or enter text to search by file name): ' ],'s');
                while isempty(str2num(a))
                    clc;
                    eval(['minilist=dir(''' a '*.mat'');']); 
                    fred=struct2cell(minilist);
                    if ~isempty(fred)
                        fred2=struct2cell(files);
                        somenames=char(fred(1,:)');
                        allnames=char(fred2(1,:)');
                        numbers=find(strcmp(fred2(1,:)',fred(1,1)') ):(find(strcmp(fred2(1,:)',fred(1,1)') )+length(fred)-1);
                        spacer(1:length(fred))= ' ';
                        disp([num2str(numbers') spacer' somenames]);
                    else
                        eval(['dir(''' a '*.mat'')']); 
                    end
                    a=input(['\nGoTo File Number(or enter text to search by file name): ' ],'s');
                    clear spacer numbers allnames somenames fred2 fred
                end
                sac_quad=100;
                file=str2num(a);
                clear a;    
                redraw=8;   
            case 110, % n for next quad
                sac_quad=min([4 sac_quad+1]); 
                fix_dur=1;
                %       redraw=1;
                %       find_tgt_sac=1; 
                %       find_all_sac=1;
                plot_which=0;                
                redraw=8;                
            case 112, 
                pause; % p for pause
            case 113, % q for no x_adjust of y_adjust
                if gca==h_trial_plot % top trial by trial xy position plot
                    C.x_adj(which_trials(round(y)))=0;
                    C.y_adj(which_trials(round(y)))=0;
                    redraw=8;                
                end
            case 115 % s for save
                save(lower([C.name 'C.mat']), 'C');
                disp([' saved file: ' C.name 'C.mat']);
            otherwise % loop around but don't waist time redrawing
                %       find_tgt_sac=0;
                %       find_all_sac=0;
                button
                redraw=0;
        end % switch button
    end %quad    
end% file
set(1,'position',[scnsize(3)/3 scnsize(4)/3 scnsize(3)/3 scnsize(4)/3])
uimenufcn(gcf,'WindowCommandWindow');
clc;
disp(' ')
disp('FIN ')

return


%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
%
function C=refind_saccade_internal(C,plot_which)

fast_threshold=40
[vel_x1 vel_y1 speed1]=velocity_speed(C.eye_x,C.eye_y,C.time);

speed=speed1(C.e_start(plot_which):C.e_end(plot_which));
time= C.time (C.e_start(plot_which):C.e_end(plot_which))-C.cue_tgt_on(plot_which);
eye_y=C.eye_y(C.e_start(plot_which):C.e_end(plot_which));
eye_x=C.eye_x(C.e_start(plot_which):C.e_end(plot_which));

fix_noise=speed(speed<50); % most people use a fixed 50dps for saccade onset. here i remove all speeds over 70dps ... 
sac_thres=max([20 mean(fix_noise)+(2*std(fix_noise))]); % and find the mean and 3std to create a variable threshold to compensate for different noise levels
sac_pts=find(speed>(sac_thres)); % sometimes 50's too low and sometimes it's too high.
sac_start_pos=(sac_pts(find(diff(sac_pts)>3)+1));
sac_start_pos=[sac_pts(1); sac_start_pos];
sac_end_pos=(sac_pts(find(diff(sac_pts)>3)));
sac_end_pos=[sac_end_pos;sac_pts(end)];
sac_start_times=time(sac_start_pos);
sac_end_times=time(sac_end_pos);
sac_dur=sac_end_times-sac_start_times; % make sure the 'saccades' last... 
sac_start_pos(sac_dur<20)=[];% ignore if too short: <20 ms long
sac_end_pos  (sac_dur<20)=[];% ignore if too short: <20 ms long

sac_start_pos2=sac_start_pos; % for interactive section
sac_end_pos2=sac_end_pos; % for interactive section
sac_start_times2=time(sac_start_pos2);% for interactive section
sac_end_times2=time(sac_end_pos2);% for interactive section

clear sac_dur;
sac_pts2=[];
fast_enought=[];
for i=1:length(sac_start_pos)
    sac_pts2=[sac_pts2 sac_start_pos(i):sac_end_pos(i)];
    fast_enought(i)=sum(speed(sac_start_pos(i):sac_end_pos(i))>50);
end
sac_start_pos(fast_enought==0)=[];% ignore if too slow: peak speed <=50 dps 
sac_end_pos  (fast_enought==0)=[];% ignore if too slow: peak speed <=50 dps 

sac_start_times=time(sac_start_pos);
sac_end_times=time(sac_end_pos);
%%%%%%%%%%%%%%%%%%%%%%%
%find tgt sac
bad_sac=0;
bad_sac(length(sac_start_times),1)=0;%create a fuzzy boolean
bad_sac(sac_start_times<100)=1; % ditch if too early
bad_sac(sac_start_times>1800)=1; % ditch if too late
%bad_sac(abs_speed(find_any(temp_eye_time,(round((sac_end_times-sac_start_times)/2)+sac_start_times)))<120)=1; % ditch if too slow <120 dps
if length(sac_start_pos)>1 % if multiple saccades
    bad_sac([abs(eye_x(sac_start_pos))>5 & abs(eye_y(sac_start_pos))>5 ])=1; % if the saccade starts with the eye 6 deg (x&y) away from the fix )
end
tsac_on_time =min(sac_start_times(find(~bad_sac))); %find first saccade that matches guidlines
tsac_off_time=min(sac_end_times  (find(~bad_sac))); %find first saccade that matches guidlines
tsac_on_pos  =min(sac_start_pos  (find(~bad_sac))); %find first saccade that matches guidlines
tsac_off_pos =min(sac_end_pos    (find(~bad_sac))); %find first saccade that matches guidlines
tsac_range=tsac_on_pos:tsac_off_pos;


button=0;
do_recalc=0;

while button<2
    fig(200);clf; 
    set(gcf,'Position',[2 342 1275 592])
    subplot(2,1,1);hold on; tickout; xlim([-2000 2000])
    plot(time,speed,'.-g')
    plot(time(sac_pts2),speed(sac_pts2),'.','color',[.8 .8 .8]);
    vline(sac_start_times2);
    if sac_start_times
        vline(sac_start_times,'k');
    end
    hline(sac_thres);        
    vline(sac_start_times(bad_sac==1));
    vline(tsac_on_time,'r');
    
    
    subplot(2,1,2);hold on; tickout; xlim([-2000 2000])
    plot(time,eye_x,'.-b');
    plot(time,eye_y,'.-r');
    vline(tsac_on_time,'g');
    drawnow
    
    [x,y,button] = ginput(1);
    if length(button)==0;
        button='return'; %if you hit enter: button=[]
    end
    uistate = uiunsuspend(200);% a sub function i touched up to reenable the zoom (and other) functions; 
    
    switch button
        case 3, % right mouse button should return you to the other fig
        case 1, % left mouse button should select the saccade to be viewed 
            if (sum(x<get(gca,'xlim'))==1 & sum(y<get(gca,'ylim'))==1) % in current plot's lim's
                new_sac=find(x>sac_start_times2 & x < sac_end_times2);
                if new_sac
                    tsac_on_time=sac_start_times2(new_sac);
                    tsac_off_time=sac_end_times2(new_sac);
                else
                    tsac_on_time=[];
                    tsac_off_time=[];
                end                
            end
        case 112, 
            pause; % p for pause
            button=0;  % dont leave just yet 
            
        case 30 % up
            sac_thres=sac_thres+5
            button=0;  % dont leave just yet
            do_recalc=1;
            
        case 31 % down
            sac_thres=sac_thres-5
            button=0;  % dont leave just yet
            do_recalc=1;
            
        otherwise 
            button
            button=0;  % dont leave just yet            
    end
    if do_recalc
        do_recalc=0;
        fix_noise=speed(speed<50); % most people use a fixed 50dps for saccade onset. here i remove all speeds over 70dps ... 
        %sac_thres=max([20 mean(fix_noise)+(2*std(fix_noise))]); % and find the mean and 3std to create a variable threshold to compensate for different noise levels
        sac_pts=find(speed>(sac_thres)); % sometimes 50's too low and sometimes it's too high.
        sac_start_pos=(sac_pts(find(diff(sac_pts)>3)+1));
        sac_start_pos=[sac_pts(1); sac_start_pos];
        sac_end_pos=(sac_pts(find(diff(sac_pts)>3)));
        sac_end_pos=[sac_end_pos;sac_pts(end)];
        sac_start_times=time(sac_start_pos);
        sac_end_times=time(sac_end_pos);
        sac_dur=sac_end_times-sac_start_times; % make sure the 'saccades' last... 
        sac_start_pos(sac_dur<20)=[];% ignore if too short: <20 ms long
        sac_end_pos  (sac_dur<20)=[];% ignore if too short: <20 ms long
        
        sac_start_pos2=sac_start_pos; % for interactive section
        sac_end_pos2=sac_end_pos; % for interactive section
        sac_start_times2=time(sac_start_pos2);% for interactive section
        sac_end_times2=time(sac_end_pos2);% for interactive section
        
        clear sac_dur;
        sac_pts2=[];
        fast_enought=[];
        for i=1:length(sac_start_pos)
            sac_pts2=[sac_pts2 sac_start_pos(i):sac_end_pos(i)];
            fast_enought(i)=sum(speed(sac_start_pos(i):sac_end_pos(i))>fast_threshold);
        end
        sac_start_pos(fast_enought==0)=[];% ignore if too slow: peak speed <=50 dps 
        sac_end_pos  (fast_enought==0)=[];% ignore if too slow: peak speed <=50 dps 
        
        sac_start_times=time(sac_start_pos);
        sac_end_times=time(sac_end_pos);
        %%%%%%%%%%%%%%%%%%%%%%%
        %find tgt sac
        bad_sac=0;
        bad_sac(length(sac_start_times),1)=0;%create a fuzzy boolean
        bad_sac(sac_start_times<100)=1; % ditch if too early
        bad_sac(sac_start_times>1800)=1; % ditch if too late
        %bad_sac(abs_speed(find_any(temp_eye_time,(round((sac_end_times-sac_start_times)/2)+sac_start_times)))<120)=1; % ditch if too slow <120 dps
        if length(sac_start_pos)>1 % if multiple saccades
            bad_sac([abs(eye_x(sac_start_pos))>5 & abs(eye_y(sac_start_pos))>5 ])=1; % if the saccade starts with the eye 6 deg (x&y) away from the fix )
        end
        tsac_on_time =min(sac_start_times(find(~bad_sac))); %find first saccade that matches guidlines
        tsac_off_time=min(sac_end_times  (find(~bad_sac))); %find first saccade that matches guidlines
        tsac_on_pos  =min(sac_start_pos  (find(~bad_sac))); %find first saccade that matches guidlines
        tsac_off_pos =min(sac_end_pos    (find(~bad_sac))); %find first saccade that matches guidlines
        tsac_range=tsac_on_pos:tsac_off_pos;
    end
end

if tsac_on_time
    C.srt(plot_which)=tsac_on_time;
    C.sac_on_loc(plot_which) =find(C.time==tsac_on_time+C.cue_tgt_on(plot_which));
    C.sac_off_loc(plot_which)=find(C.time==tsac_off_time+C.cue_tgt_on(plot_which));
    C.sac_thres(plot_which)=sac_thres;
end

return;

































function C=corrective_srt(C,plot_which)
C.corrective_sac(length(C.srt))=0;
do_recalc=1;
button=0;
fast_threshold=50
[vel_x1 vel_y1 speed1]=velocity_speed(C.eye_x,C.eye_y,C.time);

speed=speed1(C.e_start(plot_which):C.e_end(plot_which));
time= C.time (C.e_start(plot_which):C.e_end(plot_which))-C.cue_tgt_on(plot_which);
eye_y=C.eye_y(C.e_start(plot_which):C.e_end(plot_which));
eye_x=C.eye_x(C.e_start(plot_which):C.e_end(plot_which));

fix_noise=speed(speed<50); % most people use a fixed 50dps for saccade onset. here i remove all speeds over 70dps ... 
sac_thres=max([20 mean(fix_noise)+(2*std(fix_noise))]); % and find the mean and 3std to create a variable threshold to compensate for different noise levels
sac_pts=find(speed>(sac_thres)); % sometimes 50's too low and sometimes it's too high.
sac_start_pos=(sac_pts(find(diff(sac_pts)>3)+1));
sac_start_pos=[sac_pts(1); sac_start_pos];
sac_end_pos=(sac_pts(find(diff(sac_pts)>3)));
sac_end_pos=[sac_end_pos;sac_pts(end)];
sac_start_times=time(sac_start_pos);
sac_end_times=time(sac_end_pos);
sac_dur=sac_end_times-sac_start_times; % make sure the 'saccades' last... 
sac_start_pos(sac_dur<20)=[];% ignore if too short: <20 ms long
sac_end_pos  (sac_dur<20)=[];% ignore if too short: <20 ms long

sac_start_pos2=sac_start_pos; % for interactive section
sac_end_pos2=sac_end_pos; % for interactive section
sac_start_times2=time(sac_start_pos2);% for interactive section
sac_end_times2=time(sac_end_pos2);% for interactive section

clear sac_dur;
sac_pts2=[];
fast_enought=[];
for i=1:length(sac_start_pos)
    sac_pts2=[sac_pts2 sac_start_pos(i):sac_end_pos(i)];
    fast_enought(i)=sum(speed(sac_start_pos(i):sac_end_pos(i))>50);
end
sac_start_pos(fast_enought==0)=[];% ignore if too slow: peak speed <=50 dps 
sac_end_pos  (fast_enought==0)=[];% ignore if too slow: peak speed <=50 dps 

sac_start_times=time(sac_start_pos);
sac_end_times=time(sac_end_pos);

%find tgt sac
bad_sac=0;
bad_sac(length(sac_start_times),1)=0;%create a fuzzy boolean
bad_sac(sac_start_times<C.srt(plot_which))=1; % ditch if too early
bad_sac(sac_start_times>1800)=1; % ditch if too late
%bad_sac(abs_speed(find_any(temp_eye_time,(round((sac_end_times-sac_start_times)/2)+sac_start_times)))<120)=1; % ditch if too slow <120 dps
if length(sac_start_pos)>1 % if multiple saccades
    bad_sac([abs(eye_x(sac_start_pos))>5 & abs(eye_y(sac_start_pos))>5 ])=1; % if the saccade starts with the eye 6 deg (x&y) away from the fix )
end
csac_on_time =min(sac_start_times(find(~bad_sac))); %find first saccade that matches guidlines
csac_off_time=min(sac_end_times  (find(~bad_sac))); %find first saccade that matches guidlines
csac_on_pos  =min(sac_start_pos  (find(~bad_sac))); %find first saccade that matches guidlines
csac_off_pos =min(sac_end_pos    (find(~bad_sac))); %find first saccade that matches guidlines
csac_range=csac_on_pos:csac_off_pos;

while button<2
    fig(200);clf; 
    set(gcf,'Position',[2 342 1275 592])
    subplot(2,1,1);hold on; tickout; xlim([-2000 2000])
    plot(time,speed,'.-g')
    plot(time(sac_pts2),speed(sac_pts2),'.','color',[.8 .8 .8]);
    vline(sac_start_times2);
    if sac_start_times
        vline(sac_start_times,'k');
    end
    hline(sac_thres);        
    vline(sac_start_times(bad_sac==1));
    vline(csac_on_time,'r');
    
    
    subplot(2,1,2);hold on; tickout; xlim([-2000 2000])
    plot(time,eye_x,'.-b');
    plot(time,eye_y,'.-r');
    vline(csac_on_time,'g');
     drawnow
        
    [x,y,button] = ginput(1);
    if length(button)==0;
        button='return'; %if you hit enter: button=[]
    end
    uistate = uiunsuspend(200);% a sub function i touched up to reenable the zoom (and other) functions; 
    
    switch button
        case 3, % right mouse button should return you to the other fig
        case 1, % left mouse button should select the saccade to be viewed 
            if (sum(x<get(gca,'xlim'))==1 & sum(y<get(gca,'ylim'))==1) % in current plot's lim's
                new_sac=find(x>sac_start_times2 & x < sac_end_times2);
                if new_sac
                    csac_on_time=sac_start_times2(new_sac);
                    csac_off_time=sac_end_times2(new_sac);
                else
                    csac_on_time=[];
                    csac_off_time=[];
                end                
            end
        case 112, 
            pause; % p for pause
            button=0;  % dont leave just yet 
            
        case 30 % up
            sac_thres=sac_thres+5
            button=0;  % dont leave just yet
            do_recalc=1;
            
        case 31 % down
            sac_thres=sac_thres-5
            button=0;  % dont leave just yet
            do_recalc=1;
            
        otherwise 
            button
            button=0;  % dont leave just yet            
    end
    if do_recalc
        do_recalc=0;
        fix_noise=speed(speed<50); % most people use a fixed 50dps for saccade onset. here i remove all speeds over 70dps ... 
        %sac_thres=max([20 mean(fix_noise)+(2*std(fix_noise))]); % and find the mean and 3std to create a variable threshold to compensate for different noise levels
        sac_pts=find(speed>(sac_thres)); % sometimes 50's too low and sometimes it's too high.
        sac_start_pos=(sac_pts(find(diff(sac_pts)>3)+1));
        sac_start_pos=[sac_pts(1); sac_start_pos];
        sac_end_pos=(sac_pts(find(diff(sac_pts)>3)));
        sac_end_pos=[sac_end_pos;sac_pts(end)];
        sac_start_times=time(sac_start_pos);
        sac_end_times=time(sac_end_pos);
        sac_dur=sac_end_times-sac_start_times; % make sure the 'saccades' last... 
        sac_start_pos(sac_dur<20)=[];% ignore if too short: <20 ms long
        sac_end_pos  (sac_dur<20)=[];% ignore if too short: <20 ms long
        
        sac_start_pos2=sac_start_pos; % for interactive section
        sac_end_pos2=sac_end_pos; % for interactive section
        sac_start_times2=time(sac_start_pos2);% for interactive section
        sac_end_times2=time(sac_end_pos2);% for interactive section
        
        clear sac_dur;
        sac_pts2=[];
        fast_enought=[];
        for i=1:length(sac_start_pos)
            sac_pts2=[sac_pts2 sac_start_pos(i):sac_end_pos(i)];
            fast_enought(i)=sum(speed(sac_start_pos(i):sac_end_pos(i))>fast_threshold);
        end
        sac_start_pos(fast_enought==0)=[];% ignore if too slow: peak speed <=50 dps 
        sac_end_pos  (fast_enought==0)=[];% ignore if too slow: peak speed <=50 dps 
        
        sac_start_times=time(sac_start_pos);
        sac_end_times=time(sac_end_pos);
        %%%%%%%%%%%%%%%%%%%%%%%
        %find tgt sac
        bad_sac=0;
        bad_sac(length(sac_start_times),1)=0;%create a fuzzy boolean
        bad_sac(sac_start_times<100)=1; % ditch if too early
        bad_sac(sac_start_times>1800)=1; % ditch if too late
        %bad_sac(abs_speed(find_any(temp_eye_time,(round((sac_end_times-sac_start_times)/2)+sac_start_times)))<120)=1; % ditch if too slow <120 dps
        if length(sac_start_pos)>1 % if multiple saccades
            bad_sac([abs(eye_x(sac_start_pos))>5 & abs(eye_y(sac_start_pos))>5 ])=1; % if the saccade starts with the eye 6 deg (x&y) away from the fix )
        end
        csac_on_time =min(sac_start_times(find(~bad_sac))); %find first saccade that matches guidlines
        csac_off_time=min(sac_end_times  (find(~bad_sac))); %find first saccade that matches guidlines
        csac_on_pos  =min(sac_start_pos  (find(~bad_sac))); %find first saccade that matches guidlines
        csac_off_pos =min(sac_end_pos    (find(~bad_sac))); %find first saccade that matches guidlines
        csac_range=csac_on_pos:csac_off_pos;
    end
end

     C.corrective_sac(plot_which)=csac_on_time;
   
end